package com.itita.ww2.handler.requesthandler.account;

import java.sql.SQLException;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.smartfoxserver.v2.entities.User;
import com.smartfoxserver.v2.entities.data.ISFSObject;
import com.smartfoxserver.v2.entities.data.SFSObject;
import com.itita.ww2.core.MessageHandler;
import com.itita.ww2.core.WW2Exception;
import com.itita.ww2.enums.WW2ExceptionCode;
import com.itita.ww2.game.user.UserService;
import com.itita.ww2.model.user.UserProfile;
import com.itita.ww2.utils.channel.ChannelUtil;
import com.itita.ww2.utils.handler.IRequestOper;

/**
 * 帐号绑定
 * @author NorthLan
 *
 */
public class BindAccount implements IRequestOper {
	private static final Logger logger = LoggerFactory.getLogger(BindAccount.class);

	@Override
	public boolean execute(String requestCMD, User user, ISFSObject params) throws WW2Exception, SQLException {
		UserProfile userProfile = UserService.getInstance().getUserProfile(user);
		// 
		int channel = params.getInt("channel"); // 渠道号
		String token = params.getUtfString("token");

		// logger.debug(token);

		// 查看用户帐号是否被绑定过
		if (userProfile.isBindAccount()) {
			throw new WW2Exception(WW2ExceptionCode.GAME_ACC_HAS_BEEN_BOUND);
		}
		String channelId = ChannelUtil.getChannelId(channel, token);

		logger.debug("channelId: {}", channelId);

		if (channelId == null) {
			throw new WW2Exception(WW2ExceptionCode.CHANNEL_VALIED_FAILURE);
		}

		if (UserService.getInstance().isBound(channelId)) {
			throw new WW2Exception(WW2ExceptionCode.CHANNEL_ACC_HAS_BEEN_BOUND);
		}

		// 绑定
		if (!userProfile.bind(channel, channelId)) {
			throw new WW2Exception(WW2ExceptionCode.FAILURE);
		}

		// 成功
		ISFSObject backObj = SFSObject.newInstance();
		backObj.putInt("channel", channel);
		// backObj.putUtfString("channelId", channelId);
		MessageHandler.getInstance().sendMsg(requestCMD, backObj, user, null, true);
		return true;
	}
}
